package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        // 传分片参数
        doWord(shardingContext.getShardingParameter());
    }

    private void doWord(String type) {
        // 1 远程调用秒杀服务查询数据
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByType(Integer.parseInt(type));
        /**
         * result 值有几种情况
         * 1 如果调用服务挂掉了,直接走降级方法,返回就是null
         * 2 调用服务出现了异常,被统一异常处理到 {code:59291,msg:xxx
         * 3 正常返回 {code:200,msg:"操作成功",data:List<SeckillProductVo>
         */
        // 判断result不为空,状态码不等于true  code=200
        if (result!=null && !result.hasError()) {
            // 2 把查询数据放到redis中
            /**
             * hash中key的值为SeckillProductList:time
             * value:  key: seckillId   value:seckillProductVO
             */
            List<SeckillProductVo> seckillProductVoList = result.getData();
            for (SeckillProductVo seckillProductVo : seckillProductVoList) {
                redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(type),
                        seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                // 把库存放到redis当中
                // hashMap  key  Seckill
                // value  key: seckillId  value: stockCount  库存总数
               redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(type),
                       seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");

            }
            System.out.println("数据同步成功");
        }
    }
}
